<script setup lang="ts">
import ImageUpload from "~/components/ai/ImageUpload.vue";
import {useWorkEditStore} from "~/stores/workEditStore";
import ImageWaterFall, {type WaterfallImage} from "~/components/ai/ImageWaterFall.vue";
import type {Role} from "~/utils/jiangying";

const role_dialog = ref(false)
const scene_dialog = ref(false)
const uploadFile_role = ref()
const uploadFile_scene = ref()
const roleName = ref('')//角色名称
const roleFeatures = ref('')//角色特征
const voiceModel = ref(0)//声音模型

const sceneName = ref('')//场景名称
const sceneFeatures = ref('')//场景特征
const {roles, scenes, voiceModels} = storeToRefs(useWorkEditStore())

//选项卡
const tab = ref('one')

/**
 * 上传角色图片
 */
const useWorkSaveRoles = async () => {
  //   判断是否上传了图片，是否设定了角色名称
  if (!uploadFile_role.value[0] && role_edit_src.value === '') {
    useSnackbarStore().showWarningMessage('请上传一张图片')
    return
  }
  if (roleName.value === '' || roleFeatures.value === '') {
    useSnackbarStore().showWarningMessage('角色名称和特征不能为空')
    return
  }
//   将文件上传到阿里云OSS
  let imageurl = ''
  //如果有上传图片优先使用上传图片
  if (uploadFile_role.value && uploadFile_role.value[0]) {
    imageurl = await ComfyUI.uploadImage(uploadFile_role.value[0].originFileObj) || ""
  } else {
    imageurl = role_edit_src.value
  }
//   保存
  const role = {
    title: roleName.value,
    src: imageurl,
    description: roleFeatures.value,
    voicemodel_id: voiceModel.value
  } as Role
  //如果角色名称存在则替换对应元素
  const index = roles.value.findIndex(item => item.title === roleName.value)
  if (index !== -1) {
    roles.value[index] = role
    role_dialog.value = false
    uploadFile_role.value = []
    roleName.value = ''
    return
  }
  //如果角色名称不存在，则添加
  roles.value = [...roles.value, role]
  role_dialog.value = false
  uploadFile_role.value = []
  roleName.value = ''
}
/**
 * 上传场景图片
 */
const useWorkSaveScenes = async () => {
  //   判断是否上传了图片，是否设定了角色名称
  if (!uploadFile_scene.value[0] && scene_edit_src.value === '') {
    useSnackbarStore().showWarningMessage('请上传一张图片')
    return
  }
  if (sceneName.value === '' || sceneFeatures.value === '') {
    useSnackbarStore().showWarningMessage('场景名称和特征不能为空')
    return
  }
//   将文件上传到阿里云OSS
  let imageurl = ''
  //如果有上传图片优先使用上传图片
  if (uploadFile_scene.value && uploadFile_scene.value[0]) {
    //   将文件上传到阿里云OSS
    imageurl = await ComfyUI.uploadImage(uploadFile_scene.value[0].originFileObj) || ""
  } else {
    imageurl = scene_edit_src.value
  }

//   保存
  const scene = {
    id: scenes.value.length,
    title: sceneName.value,
    src: imageurl,
    description: sceneFeatures.value,
  } as Scene
  //如果场景名称名称存在则替换对应元素
  const index = scenes.value.findIndex(item => item.title === sceneName.value)
  if (index !== -1) {
    scenes.value[index] = scene
    scene_dialog.value = false
    uploadFile_scene.value = []
    sceneName.value = ''
    return
  }
  //如果场景名称不存在，则添加
  scenes.value = [...scenes.value, scene]
  scene_dialog.value = false
  uploadFile_scene.value = []
  sceneName.value = ''
}

/**
 * 图片反推提示词
 */
const handleImageReverseRole = async () => {
  if (!uploadFile_role.value && role_edit_src.value === '') {
    useSnackbarStore().showWarningMessage('请上传一张图片')
    return
  }
  let imageurl = ''
  //如果有上传图片优先使用上传图片
  if (uploadFile_role.value && uploadFile_role.value[0]) {
    imageurl = await ComfyUI.uploadImage(uploadFile_role.value[0].originFileObj)
  } else {
    imageurl = role_edit_src.value
  }

  const result = await ComfyUI.image2tagger({
    image_path_origin: imageurl
  }, {
    workflow_name: 'img2tagger_tweet'
  })
  if (result?.status === 'success') {
    roleFeatures.value += result.output
  }

}
/**
 * 图片反推场景
 */
const handleImageReverseScene = async () => {
  if (!uploadFile_scene.value && scene_edit_src.value === '') {
    useSnackbarStore().showWarningMessage('请上传一张图片')
    return
  }
  let imageurl = ''
  //如果有上传图片优先使用上传图片
  if (uploadFile_scene.value && uploadFile_scene.value[0]) {
    imageurl = await ComfyUI.uploadImage(uploadFile_scene.value[0].originFileObj)
  } else {
    imageurl = scene_edit_src.value
  }
  const result = await ComfyUI.image2tagger({
    image_path_origin: imageurl
  }, {
    workflow_name: 'img2tagger_tweet'
  })
  if (result?.status === 'success') {
    sceneFeatures.value += result.output
  }
}

/**
 * 根据索引删除role
 * @param index
 */
const handleDeleRoleByIndex = (index: number) => {
  roles.value = roles.value.filter((item, i) => i !== index)
}
/**
 * 根据索引编辑role
 */
const role_edit_src = ref('')
const handleEditRoleByIndex = (index: number) => {
  roleName.value = roles.value[index].title
  roleFeatures.value = roles.value[index].description
  role_dialog.value = true
  role_edit_src.value = roles.value[index].src
  voiceModel.value = roles.value[index].voicemodel_id
}
/**
 * 根据索引修改场景scene
 */
const scene_edit_src = ref('')
const handleEditSceneByIndex = (index: number) => {
  sceneName.value = scenes.value[index].title
  sceneFeatures.value = scenes.value[index].description
  scene_dialog.value = true
  scene_edit_src.value = scenes.value[index].src
}

/**
 * 根据索引删除场景
 */
const handleDeleSceneByIndex = (index: number) => {
  scenes.value = scenes.value.filter((item, i) => i !== index)
}
/**
 * 返回不保存数据，清空uploadfile
 */
const handleRoleBack = () => {
  uploadFile_role.value = []
  role_dialog.value = false
  // uploadFile_scene.value = []
  // roleName.value = ''
  // roleFeatures.value = ''
  // sceneName.value = ''
  // sceneFeatures.value = ''
}
/**
 * 场景界面的返回按钮操作，清空上传但是没有保存的uploadfile
 */
const handleSceneBack = () => {
  uploadFile_scene.value = []
  scene_dialog.value = false
}

/**
 * 添加角色
 */
const handleAddRole = () => {
  console.log('添加角色')
  uploadFile_role.value = []
  roleName.value = ''
  roleFeatures.value = ''
  voiceModel.value = 0
  role_dialog.value = true
}
/**
 * 添加场景
 */
const handleAddScene = () => {
  console.log('添加场景')
  uploadFile_scene.value = []
  sceneName.value = ''
  sceneFeatures.value = ''
  scene_dialog.value = true
}


</script>

<template>


  <v-container>
    <v-card>
      <v-tabs
          v-model="tab"
          bg-color="primary"
      >
        <v-tab value="one">角色</v-tab>
        <v-tab value="two">场景</v-tab>
      </v-tabs>

      <v-card-text>
        <v-window v-model="tab">
          <v-window-item value="one">
            <!--    角色设置，上传一张图片，设定一个角色名称-->
            <v-card>
              <v-sheet class="d-flex justify-space-center align-center">
                <v-card-title class="text-h5 font-weight-bold">角色管理</v-card-title>
                <!--      添加角色对话框-->
                <v-dialog
                    v-model="role_dialog"
                    max-width="80%"
                    persistent
                >
                  <template v-slot:activator="{ props: activatorProps }">
                    <v-btn color="primary" @click="handleAddRole" v-bind="activatorProps">
                      添加角色
                    </v-btn>
                  </template>
                  <v-card
                      prepend-icon="mdi-image-plus"
                      title="添加角色，并设定角色名称和特征"
                      class="text-caption font-weight-bold"
                  >
                    <v-card-title class="text-h6 font-weight-bold"></v-card-title>
                    <v-row>
                      <v-col cols="6" sm="6">

                        <v-sheet width="60%" class="mx-auto my-auto">
                          <image-upload :src="role_edit_src" v-model:uploadfile="uploadFile_role" :height="300"
                                        :width="200"/>
                        </v-sheet>

                      </v-col>
                      <v-col cols="6" sm="6">
                        <v-container>

                          <v-label class="mb-2 font-weight-bold">角色名称</v-label>
                          <v-text-field label="角色名称" v-model="roleName" placeholder="请输入角色名称"
                                        variant="outlined"></v-text-field>
                          <v-label class="mb-2 font-weight-bold">声音模型</v-label>
                          <v-select density="compact" v-model="voiceModel" :items="voiceModels" item-title="name"
                                    item-value="id" placeholder="请选择声音模型" variant="outlined"></v-select>
                          <v-sheet class="d-flex justify-space-between align-center">
                            <v-label class="mb-2 font-weight-bold">角色特征</v-label>
                            <v-btn size="small" color="primary" variant="flat" class="ma-2"
                                   @click="handleImageReverseRole">图片反推
                            </v-btn>
                          </v-sheet>

                          <v-textarea label="角色特征" v-model="roleFeatures" rows="2"
                                      placeholder="请描述角色的特质，例如头发，服饰，穿着等"
                                      variant="outlined"></v-textarea>
                        </v-container>
                      </v-col>

                    </v-row>
                    <template v-slot:actions>
                      <v-spacer></v-spacer>
                      <v-btn @click="handleRoleBack">
                        返回
                      </v-btn>
                      <v-btn color="primary" variant="flat" @click="useWorkSaveRoles">
                        保存
                      </v-btn>
                    </template>
                  </v-card>
                </v-dialog>
                <v-divider></v-divider>
              </v-sheet>

              <v-card-text>
                <!--                角色预览图片-->
                <image-water-fall v-model="roles">
                  <template v-slot:actions="{item,index}">
                    <v-btn size="x-small" icon="mdi-pencil" variant="flat"
                           @click="handleEditRoleByIndex(index)"></v-btn>
                    <v-btn size="x-small" icon="mdi-delete" @click="handleDeleRoleByIndex(index)"
                           variant="flat"></v-btn>
                  </template>
                </image-water-fall>
              </v-card-text>
            </v-card>

          </v-window-item>

          <v-window-item value="two">
            <v-card>
              <v-sheet class="d-flex justify-space-center align-center">
                <v-card-title class="text-h5 font-weight-bold">场景管理</v-card-title>
                <!--      添加场景对话框-->
                <v-dialog
                    v-model="scene_dialog"
                    max-width="80%"
                    persistent
                >
                  <template v-slot:activator="{ props: activatorProps }">
                    <v-btn color="primary" @click="handleAddScene" v-bind="activatorProps">
                      添加场景
                    </v-btn>
                  </template>
                  <v-card
                      prepend-icon="mdi-image-plus"
                      title="添加场景，并设定场景特征"
                      class="text-caption font-weight-bold"
                  >
                    <v-card-title class="text-h6 font-weight-bold"></v-card-title>
                    <v-row>
                      <v-col cols="6" sm="6">

                        <v-sheet width="60%" class="mx-auto my-auto">
                          <image-upload :src="scene_edit_src" v-model:uploadfile="uploadFile_scene" :height="300"
                                        :width="300"/>
                        </v-sheet>

                      </v-col>
                      <v-col cols="6" sm="6">
                        <v-container>

                          <v-label class="mb-2 font-weight-bold">场景名称</v-label>
                          <v-text-field label="场景名称" v-model="sceneName" placeholder="请输入场景名称"
                                        variant="outlined"></v-text-field>
                          <v-sheet class="d-flex justify-space-between align-center">
                            <v-label class="mb-2 font-weight-bold">场景特征</v-label>
                            <v-btn size="small" color="primary" variant="flat" class="ma-2"
                                   @click="handleImageReverseScene">图片反推
                            </v-btn>
                          </v-sheet>

                          <v-textarea label="场景特征" v-model="sceneFeatures" rows="3"
                                      placeholder="描述场景的特征，比如远景近景，大致的场景的描述"
                                      variant="outlined"></v-textarea>
                        </v-container>
                      </v-col>

                    </v-row>
                    <template v-slot:actions>
                      <v-spacer></v-spacer>
                      <v-btn @click="handleSceneBack">
                        返回
                      </v-btn>
                      <v-btn color="primary" variant="flat" @click="useWorkSaveScenes">
                        保存
                      </v-btn>
                    </template>
                  </v-card>
                </v-dialog>
                <v-divider></v-divider>
              </v-sheet>

              <v-card-text>
                <image-water-fall v-model="scenes">
                  <template v-slot:actions="{item,index}">
                    <v-btn size="x-small" icon="mdi-pencil" variant="flat"
                           @click="handleEditSceneByIndex(index)"></v-btn>
                    <v-btn size="x-small" icon="mdi-delete" @click="handleDeleSceneByIndex(index)"
                           variant="flat"></v-btn>
                  </template>
                </image-water-fall>
              </v-card-text>
            </v-card>
          </v-window-item>
        </v-window>
      </v-card-text>
    </v-card>


  </v-container>

</template>

<style scoped lang="scss">

</style>